# -*- encoding: utf-8 -*-

"""
@File:      tc_python_mako_func_002.py
@Time:      2024/03/19 14:33:20
@Author:    chenchunhu
@Version:   1.0
@Contact:   wb-cch358909@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    chenchunhu
"""

from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_python_mako_func_002.yaml for details

    :avocado: tags=P2,noarch,local,fix,python
    """
    PARAM_DIC = {"pkg_name": "python3-mako"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)

        cmdline = """cat > base_template.html  << 'EOF'
<html>
<head>
    <title>${title | h}</title>
</head>
<body>
    <%block name="header">
        <h1>This is the header</h1>
    </%block>

    <%block name="content"/>
    
    <%block name="footer">
        <footer>This is the footer</footer>
    </%block>
</body>
</html>
EOF"""
        self.cmd(cmdline)

        cmdline = """cat > child_template.html  << 'EOF'
<%inherit file="base_template.html"/>

<%!
def custom_method(x):
    return x.upper()
%>

<%block name="content">
    <div>
        % for item in items:
            <p>${custom_method(item)}</p>
        % endfor
    </div>
</%block>
EOF"""
        self.cmd(cmdline)

        cmdline = """cat > mako_test2.py  << 'EOF'
from mako.lookup import TemplateLookup

# 假设我们有一个 base_template.html 作为基础，然后我们在子模板
# child_template.html 中继承它。

# 创建 TemplateLookup 对象指定模板文件夹
lookup = TemplateLookup(directories=['./'])

# 读取子模板并进行渲染
tmpl = lookup.get_template('child_template.html')
rendered_html  = tmpl.render(title='My Test Page', items=['one', 'two', 'three'])

with open('mako_test2.html', 'w') as f:
    f.write(rendered_html)
EOF"""
        self.cmd(cmdline)

    def test(self):
        self.cmd("python3 mako_test2.py")
        code, mako_result = self.cmd("cat mako_test2.html")
        self.assertIn("My Test Page", mako_result)

    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf mako_test2.py mako_test2.html base_template.html child_template.html")